package com.github.shiqiyue.app.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/***
 * HttpServletRequest 工具类
 *
 * @author wenyao.wu
 */
public class HttpServletRequestUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpServletRequestUtils.class);

    /***
     * 获取HttpServletRequest
     * @return
     */
    public static HttpServletRequest getRequest() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            return request;
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }

    /***
     * 获取Session
     * @return
     */
    public static HttpSession getSession() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        return request.getSession();
    }

    /***
     * 获取IP地址
     * @return
     */
    public static String getIp() {
        return IpUtils.getIpAddr(getRequest());
    }
}
